<template>
  <div class="app-container">
    <!--    <el-alert-->
    <!--      v-show="!loading"-->
    <!--      :title="'websocket '+$t('OFFLINE')"-->
    <!--      type="error"-->
    <!--      :close-text="$t('confirm')"-->
    <!--      @close="initSocket"-->
    <!--    />-->
    <el-row :gutter="10">
      <el-col :span="6">
        <div>
          <el-checkbox v-model="checkAll" style="margin-bottom: 8px;margin-left: 30px" :indeterminate="isIndeterminate"
                       @change="handleCheckAllChange"
          >{{ $t('all') }}
          </el-checkbox>
          <div v-for="(sensor,sensorIndex) in device.sensorList" :key="sensorIndex">
            <div>
              <div style="padding:0 20px">
                <div style="margin-bottom: 13px;font-size: 15px;margin-left: 10px">
                  {{ sensor.sensorName }}
                  <span style="color: #34bfa3;margin-left: 13px">[{{ formatSensorType(sensor.type) }}{{
                      $t('port')
                    }}:{{ sensor.port }}]</span>
                </div>
                <div v-for="(explain,index3) in sensor.explainList" :key="index3" style="margin-bottom:8px">
                  <div class="item">
                    <div>
                      <el-checkbox v-model="explain.checked" style="width: 20px" @change="addCanvas(sensor,explain)"/>
                      <span style="color: #99a9bf;font-size: 13px">{{ explain.name }}</span>
                    </div>
                    <div v-if="enableEval === '1' ? explain.value.length < 6 : explain.rawValue.length < 6"
                         style="color: #606266;font-size: 13px"
                    >
                      <span style="margin-right: 5px">{{ enableEval === '1' ? explain.value : explain.rawValue }}</span>
                      <span>{{ explain.unit }}</span>
                    </div>
                  </div>
                </div>
                <el-divider/>
              </div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="18">
        <el-row :gutter="5">
          <el-col
            v-for="(item,index) in canvasList"
            :key="index"
            :xs="24"
            :sm="24"
            :md="12"
            :lg="12"
            :xl="8"
            style="margin-top: 10px"
          >
            <template v-if="item.type === 'line'">
              <div
                class="item"
                style="height: 350px;margin:0px;padding: 10px;"
              >
                <line-chart :title="item.name" :subtext="item.sensorName" :chart-data="item"
                            style="width: 100%;height: 330px;"
                />
              </div>
            </template>
            <template v-else>
              <div
                class="item"
                style="height: 350px;margin:0px;padding: 10px;"
              >
                <el-table
                  :data="item.data"
                  style="width: 100%;"
                  height="325"
                >
                  <el-table-column prop="value">
                    <template slot="header" slot-scope="scope">
                      <span>{{ item.name }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="date"/>
                </el-table>
              </div>
            </template>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <div>
      <el-switch
        v-model="enableEval"
        active-value="1"
        inactive-value="0"
        :active-text="$t('enable')+$t('script')"
        @change="enableEvalChange"
      />
      <el-switch
        v-model="showHidden"
        active-value="1"
        inactive-value="0"
        :active-text="$t('show') +$t('hidden')"
        @change="showHiddenChange"
      />
      <el-switch
        v-model="addFrame"
        active-value="1"
        inactive-value="0"
        :active-text="$t('add')+$t('frame')"
        @change="addFrameChange"
      />
    </div>

    <el-dialog
      :visible.sync="showSetting"
      :title="deviceName"
      width="1200px"
      top="15px"
    >
      <device-setting
        :device-core="deviceCore"
        class="uni-scroll"
        style="height: 600px"
      />
    </el-dialog>

    <el-button
      icon="el-icon-setting"
      circle
      type="primary"
      style="position: fixed;bottom: 30px;right: 20px;z-index: 1000"
      @click="deviceSetting"
    />

  </div>
</template>

<script>
import DeviceSetting from '@/components/DeviceSetting'
import { failureNotice, formatDate, formatSensorType } from '@/util/common'
import { getAddFrame, getEnableEval, getShowHidden, setAddFrame, setEnableEval, setShowHidden } from '@/util/storage'
import { detailsDevice } from '@/api/iot/iotDeviceApi'
import { listSensorWith } from '@/api/iot/iotDeviceSensorApi'
import LineChart from '@/components/Chart/LineChart'
import resize from '@/components/Mixins/resize'
import { leaveWebSocket, listenWebSocket } from '@/util/websocketTool'

export default {
  name: 'SensorRealTime',
  components: {
    LineChart,
    DeviceSetting
  },
  mixins: [resize],
  data() {
    return {
      checkAll: true,
      isIndeterminate: true,
      showSetting: false,
      // loading: false,
      deviceCore: null,
      deviceName: null,
      device: {},
      canvasList: [],
      // ws: null,
      enableEval: getEnableEval(),
      showHidden: getShowHidden(),
      addFrame: getAddFrame(),
      wsMonitor: {
        room: 'iot:device:' + this.deviceCore,
        onmessage: this.onSocketMsg
      }
    }
  },
  beforeDestroy() {
    // if (this.ws == null) {
    //   return
    // }
    // this.ws.send(JSON.stringify({
    //   cmd: 'unBindRoom',
    //   param: 'iot:device:' + this.deviceCore
    // }))
    this.closeSocket()
  },
  mounted() {
    const param = this.$route.query
    this.deviceCore = param.deviceCore
    this.deviceName = param.deviceName
    this.init()
    if (!this.deviceName) {
      this.deviceName = this.deviceCore
    }
    this.setTagsViewTitle()
  },
  methods: {
    enableEvalChange() {
      setEnableEval(this.enableEval)
    },
    showHiddenChange() {
      setShowHidden(this.showHidden)
      this.init()
    },
    addFrameChange() {
      setAddFrame(this.addFrame)
    },
    handleCheckAllChange() {
      if (this.checkAll) {
        this.device.sensorList.forEach(sensor => {
          sensor.explainList.forEach(explain => {
            explain.checked = true
            this.addCanvas(sensor, explain)
          })
        })
      } else {
        this.device.sensorList.forEach(sensor => {
          sensor.explainList.forEach(explain => {
            explain.checked = false
            this.addCanvas(sensor, explain)
          })
        })
      }
      this.isIndeterminate = false
    },
    formatSensorType(type) {
      return formatSensorType(this, type)
    },
    deviceSetting() {
      this.showSetting = true
    },
    formatDate(time) {
      return formatDate(this, time)
    },
    addCanvas(sensor, explain) {
      for (let i = 0, j = this.canvasList.length; i < j; i++) {
        const canvas = this.canvasList[i]
        if (canvas.port === explain.port && canvas.keyName === explain.keyName) {
          this.canvasList.splice(i, 1)
          return
        }
      }
      // for (let i = 0, j = this.device.sensorList.length; i < j; i++) {
      //   const s = this.device.sensorList[i]
      //   if (s.sensorId === sensor.sensorId) {
      //     for (let n = 0, m = s.explainList.length; n < m; n++) {
      //       const e = s.explainList[n]
      //       if (e.keyName === explain.keyName) {
      //         break
      //       }
      //     }
      //     this.device.sensorList.splice(i, 1, s)
      //   }
      // }
      explain.sensorName = sensor.sensorName + '[' + this.formatSensorType(sensor.type) + this.$t('port') + sensor.port + ']'

      this.canvasList.push({
        ...explain,
        value: '_',
        dataList: [],
        dateList: [],
        data: []
      })
    },

    setTagsViewTitle() {
      this.tempRoute = Object.assign({}, this.$route)
      const route = Object.assign({}, this.tempRoute, {
        title: `${this.deviceName}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    closeSocket() {
      leaveWebSocket(this.wsMonitor)
      // this.loading = false
      // if (this.ws) {
      //   this.ws.onclose = null
      //   this.ws.close()
      //   this.ws = null
      // }
    },
    onSocketMsg(nowData) {
      if (nowData.type === 'deviceData') {
        const data = JSON.parse(nowData.msg)
        if (data.deviceUpload) {
          if (data.deviceUpload.sensorList && data.deviceUpload.sensorList.length > 0) {
            data.deviceUpload.sensorList.forEach(sensor => {
              if (sensor.explainList != null && sensor.explainList.length > 0) {

                for (let i = 0, j = this.canvasList.length; i < j; i++) {
                  const canvas = this.canvasList[i]
                  let have = false
                  sensor.explainList.forEach(explain => {
                    if (canvas.port === sensor.port && explain.keyName === canvas.keyName) {
                      if (canvas.type === 'line') {
                        if (canvas.dataList.length >= 60) {
                          canvas.dataList.splice(0, 1)
                          canvas.dateList.splice(0, 1)
                        }
                        canvas.dataList.push(this.enableEval === '1' ? explain.value : explain.rawValue)
                        canvas.dateList.push(this.formatDate(nowData.timestamp))
                      } else {
                        if (canvas.data.length >= 60) {
                          canvas.data.splice(0, 1)
                        }
                        canvas.data.push({
                          value: this.enableEval === '1' ? explain.value : explain.rawValue,
                          date: this.formatDate(nowData.timestamp)
                        })
                      }
                      canvas.value = this.enableEval === '1' ? explain.value : explain.rawValue
                      canvas.valueDate = nowData.timestamp
                      this.canvasList.splice(i, 1, canvas)
                      this.have = true
                    }
                  })
                  if (!have && this.addFrame === '1') {
                    if (canvas.type === 'line') {
                      if (canvas.dataList.length >= 60) {
                        canvas.dataList.splice(0, 1)
                        canvas.dateList.splice(0, 1)
                      }
                      canvas.dataList.push(this.enableEval === '1' ? canvas.value : canvas.rawValue)
                      canvas.dateList.push(this.formatDate(nowData.timestamp))
                    } else {
                      if (canvas.data.length >= 60) {
                        canvas.data.splice(0, 1)
                      }
                      canvas.data.push({
                        value: this.enableEval === '1' ? canvas.value : canvas.rawValue,
                        date: this.formatDate(nowData.timestamp)
                      })
                    }
                    canvas.valueDate = nowData.timestamp
                  }
                }
              }
            })
          }
        }
      }
    },
    // initSocket() {
    //   const that = this
    //   this.closeSocket()
    //   this.ws = newWebSocket()
    //   this.ws.onopen = () => {
    //     that.loading = true
    //     that.ws.send(JSON.stringify({
    //       cmd: 'bindRoom',
    //       param: 'iot:device:' + that.deviceCore
    //     }))
    //   }
    //   this.ws.onerror = function(e) {
    //     console.error('WebSocket is error' + e.code + ' ' + e.reason + ' ' + e.wasClean)
    //     that.loading = false
    //     that.closeSocket()
    //     setTimeout(function() {
    //       that.initSocket()
    //     }, 20000)
    //   }
    //   this.ws.onclose = function(e) {
    //     console.error('WebSocket is close' + e.code + ' ' + e.reason + ' ' + e.wasClean)
    //     that.loading = false
    //     setTimeout(function() {
    //       that.initSocket()
    //     }, 20000)
    //   }
    //   this.ws.onmessage = function(msg) {
    //     const nowData = JSON.parse(msg.data)
    //     if (nowData.type === 'deviceData') {
    //       const data = JSON.parse(nowData.msg)
    //       if (data.deviceUpload) {
    //         if (data.deviceUpload.sensorList && data.deviceUpload.sensorList.length > 0) {
    //           data.deviceUpload.sensorList.forEach(sensor => {
    //             if (sensor.explainList != null && sensor.explainList.length > 0) {
    //               sensor.explainList.forEach(explain => {
    //                 for (let i = 0, j = that.canvasList.length; i < j; i++) {
    //                   const canvas = that.canvasList[i]
    //                   if (canvas.port === sensor.port && explain.keyName === canvas.keyName) {
    //                     if (canvas.type === 'line') {
    //                       if (canvas.dataList.length >= 50) {
    //                         canvas.dataList.splice(0, canvas.dataList.length - 50)
    //                         canvas.dateList.splice(0, canvas.dateList.length - 50)
    //                       }
    //                       canvas.dataList.push(that.enableEval === '1' ? explain.value : explain.rawValue)
    //                       canvas.dateList.push(that.formatDate(nowData.timestamp))
    //                     } else {
    //                       if (canvas.data.length >= 50) {
    //                         canvas.data.splice(0, canvas.data.length - 50)
    //                       }
    //                       canvas.data.push({
    //                         value: that.enableEval === '1' ? explain.value : explain.rawValue,
    //                         date: that.formatDate(nowData.timestamp)
    //                       })
    //                     }
    //                     canvas.value = that.enableEval === '1' ? explain.value : explain.rawValue
    //                     canvas.valueDate = nowData.timestamp
    //                     that.canvasList.splice(i, 1, canvas)
    //                   }
    //                 }
    //               })
    //             }
    //           })
    //         }
    //       }
    //     }
    //   }
    // },
    listSensorWith() {
      listSensorWith({
        deviceCore: this.deviceCore,
        hidden: this.showHidden === '1' ? null : false,
        withExplain: true,
        withParam: false,
        withSetting: false

      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.device.sensorList = data
        }
        this.handleCheckAllChange()
      })
    },
    detailsDevice() {
      detailsDevice({
        deviceCore: this.deviceCore
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          // this.initSocket()
          data.sensorList = []
          this.device = data
          this.listSensorWith()
        }
      })
    },
    init() {
      if (this.deviceCore == null || this.deviceCore === '') {
        failureNotice(this, this.$t('deviceCore'))
        return
      }
      this.wsMonitor.room = 'iot:device:' + this.deviceCore
      listenWebSocket(this.wsMonitor)
      this.detailsDevice()
    }
  }
}
</script>
<style scoped>
.item {
  display: flex;
  justify-content: space-between;
  padding: 0 10px;
  height: 25px;
  line-height: 25px;
  margin-bottom: 10px;
}

.item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
  border-radius: 12px;
}
</style>
